package main;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;

public class NetIncomePanel_controller implements ActionListener {
	private NetIncomePanel mainPanel;
	private SalaryWorker worker;
	public final int freeTax=2000;

	public NetIncomePanel_controller() {
		mainPanel = new NetIncomePanel();
		mainPanel.addListeners(this);
	}

	public Component getMainPanel() {
		return mainPanel;
	}

	private void computeResult() {
		mainPanel.updateDataFromUI();
		compute();
		mainPanel.updateUIFromData();

	}

	private void compute() {
		NetIncomePanel_bean bean=mainPanel.getBean();
		NormalTable welfareTable=mainPanel.getWelfareTable();
		NormalTable taxRatioTable=mainPanel.getTaxTable();
		
		worker=new SalaryWorker(bean.getBaseSalary(), bean.getBonus(), bean.getWorkRate(),bean.getLocation(), (WelfareRatioTableModel)welfareTable.getModel(), (TaxRatioTableModel)taxRatioTable.getModel());
		
		bean.setPureIncome(worker.getMonthlyNetIncome());
		bean.setPersonalWelfare(worker.getMonthlyPersonalWelfare());
		bean.setPersonalTax(worker.getMonthlyPersonalTax());
		bean.set_social_security_funds(worker.getMonthly_social_security_funds());
		bean.setHousingfunds(worker.getMonthlyHousingfund());
		bean.setPersonalSocialSecurity(worker.getPersonalSS());
		bean.setPersonalHousingfund(worker.getPersonalHousingfund());

	}


	@Override
	public void actionPerformed(ActionEvent e) {
		Object o = e.getSource();
		String action = e.getActionCommand();

		if (o instanceof JButton) {
			if (action.equals(Constant.action_taxRateTable)) {

				NormalTable taxTable = mainPanel.getTaxTable();

				JScrollPane scrollPane = new JScrollPane(taxTable);

				JDialog taxDlg = new JDialog((JFrame) (mainPanel.getParent()
						.getParent().getParent().getParent()));
				taxDlg.setModal(true);
				taxDlg.setTitle(Constant.action_taxRateTable);
				taxDlg.add(scrollPane);
				taxDlg.pack();
				taxDlg.setLocationRelativeTo(mainPanel);
				taxDlg.setVisible(true);
			}

			if (action.equals(Constant.action_calculate)) {
				computeResult();
			}
		}

		if (o instanceof JRadioButton) {
			if (((JRadioButton) o).isSelected()) {
				mainPanel.getBean().setLocation(action);
			}
		}

	}

}
